import React from 'react';
import { Router, Route, Link, browserHistory } from 'react-router';


import Navigation from './common/Navigation';
import api from './api';
//路由
import router from './router';

import {message,Layout,Menu,Breadcrumb, Icon ,Popover,Modal,Button,Input} from 'antd';
import {TOP_TAB} from './constants/index';
import {bind_change} from './common/State';

import 'layout.scss';
import 'antd.css';
import 'height.scss';
import 'margin.scss';
import 'flex.scss';
import 'ant_custom.scss';
const {Header,Content,Footer} = Layout;

message.config({
  top: 100,
  duration: 2,
});

export default class App extends React.Component{

    constructor(props, context){
        super(props, context);
        
        this.state={
           session:null,
           currentTab:TOP_TAB[0],
           modifyPasswordVisibility:false,
           logoutVisibility:false,
           user:{}

        };
    }

    async componentWillMount(){
        let result = await this.checkLogin();
        let pathname = location.pathname;
        let cur = '';
        if (pathname.includes("propertyData")) {
            cur = TOP_TAB[1]
        }else if (pathname.includes("underlyingAssets")) {
            cur = TOP_TAB[0]
        }else if (pathname.includes("systemManage")) {
            cur = TOP_TAB[2]
        }else{
            cur = TOP_TAB[0]
        }
        this.setState({
            currentTab:cur,
            session:result.data
        })
        // let session = await this.checkLogin();
        //
        // if(!session.cd){
        //     this.setState({
        //         session:session.data
        //     })
        // }
    }
    async checkLogin(){
        // let result = await api("/authority/check/login",{});
        // if (result.success) {
        //     this.setState({
        //         user:result.data
        //     })
        // }
        // return result;
        
        return await api('/authority/check/login',{});
    }
    // async requireAuth(nextState,replaceState){
    //     var session = await this.checkLogin();
    //     if(!session.success && session.message == "User Unauthorized"){
    //         location.href='/login?next='+(nextState.location.pathname||"/") ;
    //         return {employee:{},userPassport:{}};
    //     }
    //     return session.data;
        
    // }

    onClickMenuTab(e){
        this.setState({
            currentTab:e.key,
        })
        let pathName = '';
        switch(e.key) {
            case TOP_TAB[0]:
                pathName = '/underlyingAssets/waitingIn/list'
                break;
            case TOP_TAB[1]:
                pathName = '/propertyData/propertyData/list'
                break;
            case TOP_TAB[2]:
                pathName = '/systemManage/financeCompany/list'
                break;
        }
        browserHistory.push({pathname:pathName});
    }

    getAccountContent(){
        let {session} = this.state;
        return (
            <div style={{width:240,height:80,lineHeight:2}}>
                <div>{session.username}</div>
                <div>
                    {session.firm}/{session.apartment}
                </div>
                <div>
                    账号：{session.account} | 
                    <a
                        href='javascript:void 0'
                        onClick={() =>{
                              this.setState({
                                modifyPasswordVisibility:true,
                            })
                        }}
                      >
                      修改密码    
                    </a>
                    <i className='separator'>|</i>
                    <a
                        href='javascript:void 0'
                        onClick={() =>{
                              this.setState({
                                logoutVisibility:true,
                            })
                        }}
                      >
                      退出    
                    </a>
                </div>
            </div>
        )
    }

    async modifyPasswordConfirm(){
        let {old_password,new_password,new_password_confirm} = this.state;
        if (!old_password) {
            message.error("请输入原密码！");
            return;
        }
        if (!new_password) {
            message.error("请输入新密码！");
            return;
        }
        if (!new_password_confirm) {
            message.error("请再次输入密码！");
            return;
        }
        let result = await api("/authority/modify/password",{old_password,new_password,new_password_confirm});
        if (result.success) {
            message.success("修改成功!");
            this.setState({
                modifyPasswordVisibility:false,
            })
        }else{
            message.error(result.message);
        }

    }

    async logoutConfirm(){
        let result = await api("/authority/logout",{});
        if (result.success) {
            this.setState({
                logoutConfirm:false,
            })
            location.href="/logout";
        }
    }

    render(){
        let {session} = this.state;
        if (!session) {
            return null;
        }
        return (
            <Layout>
                <Header className="header" style={{"height":"65px"}}>
                    <div style={{"float":"left","fontSize":"28px",marginRight:"30px",color:"lightGrey"}}>瑞茂通ABS服务平台</div>
                    <Menu
                        theme="dark"
                        mode="horizontal"
                        selectedKeys={[this.state.currentTab]}
                        style={{ lineHeight: '64px',textAlgin:"center","float":"left"}}

                        onSelect={this.onClickMenuTab.bind(this)}

                    >
                        <Menu.Item key={TOP_TAB[0]}>
                          基础管理
                        </Menu.Item>
                        <Menu.Item key={TOP_TAB[1]}>
                          资产管理
                        </Menu.Item>
                        {session.role_type == "ORIGINATOR"?
                            <Menu.Item key={TOP_TAB[2]}>
                              系统管理
                            </Menu.Item>
                        :
                            null
                        }
                        
                        
                    </Menu>

                        <Popover content={this.getAccountContent()} trigger="click" placement="bottomRight">
                            <span className="text-right" style={{"float":"right",color:"lightGrey"}}>{session.username}</span>
                        </Popover>


                </Header>
                <Content style={{ padding: '0 20px' ,marginTop:'20px'}}>
                    {/*<Breadcrumb style={{ margin: '16px 0' }}>
                        <Breadcrumb.Item>Home</Breadcrumb.Item>
                        <Breadcrumb.Item>List</Breadcrumb.Item>
                        <Breadcrumb.Item>App</Breadcrumb.Item>
                    </Breadcrumb>*/}
                    <Layout>

                        <Navigation currentTab={this.state.currentTab}>
                            <Router history={browserHistory}>
                            {router.map((item,index) =>{
                                    return (<Route session={session} key={index} path={item.path} component={item.name}/>)
                                })
                            }
                            </Router>
                        </Navigation>

                    </Layout>
                </Content>

                <Modal
                    title="修改密码"
                    visible={this.state.modifyPasswordVisibility}
                    onOk={this.modifyPasswordConfirm.bind(this)}
                    width="380"
                    onCancel={() => {
                        this.setState({
                            modifyPasswordVisibility:false,
                        })
                    }}
                >
                    <Input {...this::bind_change('old_password')} placeholder="请输入原密码" className="marginT20" type="password"/>
                    <Input {...this::bind_change('new_password')} placeholder="请输入新密码" className="marginT20 marginB20" type="password"/>
                    <Input {...this::bind_change('new_password_confirm')} placeholder="请再次输入密码" className="marginB20" type="password"/>

                </Modal>

                <Modal
                    title="提示"
                    visible={this.state.logoutVisibility}
                    onOk={this.logoutConfirm.bind(this)}
                    width="380"
                    onCancel={() => {
                        this.setState({
                            logoutVisibility:false,
                        })
                    }}
                >
                    <p>您确定要退出登录吗？</p>
                </Modal>

            </Layout>
        );
    }
}
